#!/usr/bin/env python3
"""
文件处理入口脚本
用法: python process_files.py <文件路径> [--output <输出目录>]
"""

import sys
import argparse
import logging
import json
from pathlib import Path
from datetime import datetime

# 设置项目根目录为Python路径
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from data_processor.encryption import EncryptionManager
from data_processor.metadata import MetadataExtractor
from data_processor.hashing import HashGenerator
from config.settings import settings

# 配置日志
logging.basicConfig(
    level=settings.LOG_LEVEL,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(settings.LOG_FILE),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


def process_file(input_path: Path, output_dir: Path) -> dict:
    """
    处理单个文件的完整流程
    :param input_path: 输入文件路径
    :param output_dir: 输出目录
    :return: 处理结果字典
    """
    logger.info(f"开始处理文件: {input_path}")
    start_time = datetime.now()

    # 初始化组件
    enc_manager = EncryptionManager(settings.KEY_DIR)
    hasher = HashGenerator()

    # 1. 计算文件哈希
    file_hash = hasher.file_hash(input_path)
    logger.debug(f"文件哈希计算完成: {file_hash}")

    # 2. 提取元数据
    try:
        if input_path.suffix.lower() == '.json':
            metadata = MetadataExtractor.from_json(input_path)
        else:
            metadata = MetadataExtractor.from_csv(input_path)
        logger.debug("元数据提取完成")
    except Exception as e:
        logger.error(f"元数据提取失败: {e}")
        raise

    # 3. 加密原始文件
    try:
        encrypted_path = output_dir / f"encrypted_{input_path.name}"
        enc_manager.encrypt_file(input_path, encrypted_path)
        logger.debug(f"文件加密完成: {encrypted_path}")
    except Exception as e:
        logger.error(f"文件加密失败: {e}")
        raise

    # 4. 保存元数据
    try:
        meta_path = output_dir / f"metadata_{input_path.stem}.json"
        with open(meta_path, 'w') as f:
            json.dump(metadata, f, indent=2)

        # 加密元数据文件
        enc_manager.encrypt_file(meta_path)
        logger.debug(f"元数据文件加密完成: {meta_path}.enc")
    except Exception as e:
        logger.error(f"元数据保存失败: {e}")
        raise

    # 计算处理时间
    processing_time = (datetime.now() - start_time).total_seconds()

    result = {
        "input_file": str(input_path),
        "encrypted_file": str(encrypted_path),
        "metadata_file": str(meta_path),
        "file_hash": file_hash,
        "processing_time_sec": processing_time,
        "status": "success"
    }

    logger.info(f"文件处理完成: {input_path} (耗时: {processing_time:.2f}秒)")
    return result


def main():
    """命令行入口"""
    parser = argparse.ArgumentParser(description="隐私保护数据质量检查系统 - 文件处理器")
    parser.add_argument("input_file", help="要处理的输入文件路径")
    parser.add_argument("--output", "-o", default=settings.OUTPUT_DIR,
                        help="输出目录路径 (默认为项目output目录)")

    args = parser.parse_args()

    input_path = Path(args.input_file)
    output_dir = Path(args.output)

    if not input_path.exists():
        logger.error(f"输入文件不存在: {input_path}")
        sys.exit(1)

    output_dir.mkdir(exist_ok=True, parents=True)

    try:
        result = process_file(input_path, output_dir)
        print("\n处理结果:")
        print(json.dumps(result, indent=2))
    except Exception as e:
        logger.error(f"处理失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()